package com.googlecode.gwtdb.client.indexeddb.js;

import com.google.gwt.core.client.JavaScriptObject;

import com.googlecode.gwtdb.client.indexeddb.IDBCallback;
import com.googlecode.gwtdb.client.indexeddb.IDBDatabase;
import com.googlecode.gwtdb.client.indexeddb.IDBReadyState;
import com.googlecode.gwtdb.client.indexeddb.event.IDBBaseError;
import com.googlecode.gwtdb.client.indexeddb.sub.IDBOpenDBRequest;

public final class IDBOpenDBRequestJsImpl extends JavaScriptObject implements IDBOpenDBRequest {

  protected IDBOpenDBRequestJsImpl() {

  }

  @Override
  public IDBDatabase getResult() {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public IDBBaseError getError() {
    // TODO not implemented
    throw new RuntimeException("not implemented");
  }

  @Override
  public IDBReadyState getReadyState() {
    String readyState = getReadyState0();


    if ("pending".equalsIgnoreCase(readyState)) {
      return IDBReadyState.PENDING;
    }

    if (readyState == null || "done".equalsIgnoreCase(readyState)) {
      return IDBReadyState.DONE;
    }

    throw new IllegalStateException("ready state has unkown value: '" + readyState + "'");

  }

  private native String getReadyState0()/*-{
		return this.readyState;
  }-*/;

  @Override
  public native void setOnError(IDBCallback<IDBBaseError> callback) /*-{
		this.onerror = $entry(function(request) {
			callback.@com.googlecode.gwtdb.client.indexeddb.IDBCallback::onCallback(*)(request);
		});
  }-*/;

  @Override
  public native void setOnSuccess(IDBCallback<IDBOpenDBRequest> callback) /*-{
		this.onsuccess = $entry(function(request) {
			callback.@com.googlecode.gwtdb.client.indexeddb.IDBCallback::onCallback(*)(request);
		});
  }-*/;

  @Override
  public native void setOnBlocked(IDBCallback<IDBBaseError> callback) /*-{
		this.onblocked = $entry(function(request) {
			callback.@com.googlecode.gwtdb.client.indexeddb.IDBCallback::onCallback(*)(request);
		});
  }-*/;

  @Override
  public native void setOnUpgradeNeded(IDBCallback<Void> callback) /*-{
		this.onupgradeneeded = $entry(function(request) {
			callback.@com.googlecode.gwtdb.client.indexeddb.IDBCallback::onCallback(*)(request);
		});
  }-*/;

}
